var fs = require('fs');
var path = require('path');
var util = require('util');
var multiparty = require('multiparty');
var zipeUtil = require('./zipUtil.js');
var war = require('./war.js');
var buildResults = []; //已经打包完成的
var processingWar = []; //正在打包的


exports.upload = function(req, res) {
	console.log("fileUtile upload ");
	var guid = getGuid();
	var beginTime = new Date(); //开始时间
	var targetDir = path.join(__dirname, "..", "resource", "buildresult", guid);
	console.log("文件保存目录是：" + targetDir);
	if (!fs.existsSync(targetDir)) { //目录不存在
		fs.mkdirSync(targetDir);
	}
	//生成multiparty对象，并配置上传目标路径
	var form = new multiparty.Form({
		uploadDir: targetDir
	});
	//上传完成后处理
	form.parse(req, function(err, fields, files) {
		var fieldsJSON = JSON.stringify(fields, null, 2);
		console.log("fields is ..."+fieldsJSON);
		var warName = fields.warName[0];
		var servletVersion = fields.servletVersion[0];
		if (isNaN(servletVersion)) {
			servletVersion = null;
		}
		var filesTmp = JSON.stringify(files, null, 2);
		var dstPath = "";
		if (err) {
			console.log('parse error: ' + err);
		} else {
			console.log('parse files: ' + filesTmp);
			var inputFile = files.fileupload[0];
			var uploadedPath = inputFile.path;
			dstPath = path.join(targetDir, inputFile.originalFilename);
			//重命名为真实文件名
			fs.rename(uploadedPath, dstPath, function(err) {
				if (err) {
					console.log('rename error: ' + err);
				} else {
					console.log('rename ok');
					console.log("上传文件全路径是：" + dstPath);
					var endTime = new Date(); //结束时间
					var timeConsuming = endTime.getTime() - beginTime.getTime();
					console.log("上传文件" + inputFile.originalFilename + "耗费时间:" + timeConsuming + "ms");
					//war.building_war(dstPath, servletVersion, warName);
					var option = {
						"guid": guid,
						"da_path": dstPath,
						"buildPath": targetDir,
						"servletVersion": servletVersion,
						"warName": warName,
						"dnaVersion": null,
						"daName": inputFile.originalFilename,
						"date": getNow("yyyy-MM-dd hh:mm:ss"),
						"state": 0
					};
					res.json({
						success: true,
						data : option
					});
					buildResults.push(option);
					war.building_war(option, function(err, data) {
						console.log(buildResults.length);
						option.date = getNow("yyyy-MM-dd hh:mm:ss");
						option.state = 1;
						console.log("打包结束");
					});
				}
			});
		}
	});


};

var Counter = function() {
	var num = 0;
	this.up = function() {
		num++;
	};
	this.down = function() {
		num--;
		if (num == 0) {
			callback();
		}
	};
};

exports.deleteFolderOrFile = function(path) {
	var deleteFolderRecursive = function(path) {
		if (fs.existsSync(path)) { //文件存在
			if (fs.lstatSync(path).isDirectory()) { //是目录
				var files = fs.readdirSync(path);
				files.forEach(function(file, index) {
					var tempPath = path + "/" + file;
					deleteFolderRecursive(tempPath);
				});
				fs.rmdirSync(path);
			} else { //是文件
				fs.unlinkSync(path); //直接删除文件
				console.log("删除的文件是：" + path);
			}

		}
	};
	deleteFolderRecursive(path);
};


exports.getProcessingWar = function(req, res) {
	// var removeObj = [];
	// for (var i = 0; i < buildResults.length; i++) {
	// 	if (buildResults[i].state == 1) { //状态为1的全部移除
	// 		removeObj.push(buildResults[i]);
	// 	}
	// }
	// for(var i = 0 ; i < ){
	// }
	var data = {
		success: true,
		data: buildResults
	};
	console.log(data);
	res.json(data);
};

Date.prototype.Format = function(fmt) {
	var o = {
		"M+": this.getMonth() + 1, //月份   
		"d+": this.getDate(), //日   
		"h+": this.getHours(), //小时   
		"m+": this.getMinutes(), //分   
		"s+": this.getSeconds(), //秒   
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度   
		"s": this.getMilliseconds() //毫秒   
	};
	if (/(y+)/.test(fmt))
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
		if (new RegExp("(" + k + ")").test(fmt))
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
};

Array.prototype.deleteElementByValue = function(varElement) {
	var numDeleteIndex = -1;
	for (var i = 0; i < this.length; i++) {
		// 严格比较，即类型与数值必须同时相等。
		if (this[i] === varElement) {
			this.splice(i, 1);
			numDeleteIndex = i;
			break;
		}
	}
	return numDeleteIndex;
};

function getNow(fmt) {
	var time1 = new Date().Format(fmt);
	console.log(time1);
	return time1;
}

function getGuid() {
	var guid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
		var r = Math.random() * 16 | 0,
			v = c == 'x' ? r : (r & 0x3 | 0x8);
		return v.toString(16);
	});
	return guid.replace(new RegExp('-', 'g'), '');
}